package com.wangshuqi.mybatis.spring;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/*
 * 为每一个mapper接口生成一个代理对象
 * */
public class MyFactoryBean implements FactoryBean {

    private SqlSession sqlSession;

    private Class mapperClass;

    public MyFactoryBean(Class mapperClass) {
        this.mapperClass = mapperClass;
    }

    // 通过set的方式给SqlSession注入对象
    @Autowired
    public void setSqlSession(SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addMapper(mapperClass);
        this.sqlSession = sqlSessionFactory.openSession();
    }

    // 返回一个UserMapper代理对象
    @Override
    public Object getObject() throws Exception {
        return sqlSession.getMapper(mapperClass);
    }

    // 代理对象的类型为UserMapper类
    @Override
    public Class<?> getObjectType() {
        return mapperClass;
    }
}
